var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
    console.log('Time: ', Date.now())
    //模块路由中检测是否携带了 token
    if(!req.auth){
        return res.send({
            status: 403,
            message: "缺少token"
        });
    }
    next()
})
//  从db文件中导入的数据库模块
var db = require("../db/mysql");
const { json } = require('body-parser');
// 用户类型列表
/*
router.get("/list",(req,res)=>{
    db.query("SELECT id,pname,status FROM department",function(error,results){
        if(error) console.log(error)
        console.log(results)
        
        [
            RowDataPacket { id: 1, pname: '宿管', status: 1 },
            RowDataPacket { id: 2, pname: '总务', status: 1 },
            RowDataPacket { id: 3, pname: '维修师傅', status: 1 },
            RowDataPacket { id: 4, pname: '老师', status: 1 },
            RowDataPacket { id: 5, pname: '学生', status: 1 }
        ]
        
        console.log(results[0])
        console.log(results[0].id)
        console.log(results[0].pname)
        console.log(results[0].status)
        let partname 
        let id
        let status
        let arr = []
        for(let i =0;i < results.length; i++){
            partname = results[i].pname
            id = results[i].id
            status = results[i].status
            arr.push({partname,id,status})
        }
        res.send({ code: 0, msg: "用户类型列表", data: arr })
    })
})
*/
// 部门列表
router.get('/list', (req, res) => {
    // 获取token
    console.log(req.auth)  //获取token中信息:{ uid: 9, account: '15527098790', iat: 1721979755, exp: 1722238955 }
    let uid = req.auth.uid;
    // 获取url中的参数 ?page=1&page_size=3,参数放在req.query中 { page: '1', page_size: '3' }
    let {page,page_size} = req.query;
    // 查询limit
    let start = (page - 1) * page_size;
    let limit = ` limit ${start}, ${page_size}` //limit 0,3
    let selectSQL = `
    SELECT id,pname,status  
    FROM department ${limit}`;

    db.query(selectSQL, function (error, results) {
        if(error) console.log(error)
        var id;
        var pname;
        var status;
        let arr = [];
        for (let i = 0; i < results.length; i++) {
            id=results[i].id
            pname = results[i].pname
            if(results[i].status === 1){
                status = '启用'
            }else if(results[i].status === 0){
                status = '禁用'
            }
            arr.push({ id,pname, status })

            // console.log(part)
        }
        //总条数
        db.query("SELECT count(id) as total FROM department",(err,data)=>{
            console.log("total:",data)
            let totalNum = data[0]?.total
            res.json({ code: 0, msg: "信息详情", data: {list:arr,totalNum} })
        })
    })
})

// 用户类型添加
router.post("/add",(req,res)=>{
    // 先获取用户的请求数据，存到变量“body”中
    var body = req.body
    // 用结构复制把用户请求数据里面的的“uname,part,mobile, pwd”分别拿出来，方便接下来向数据库中添加数据时使用
    let { pname ,status } = body
    console.log('用户添加信息：：：'+pname,status)
    console.log(body)
    db.query('SELECT * FROM department where pname = ?', [pname], function (error, results) {
        if (results.length > 0) {

            res.send({ data: [], code: 1, msg: "此部门已经存在" }) //标准返回信息
        } else {
            db.query(
                'INSERT INTO department (pname,status) VALUES (?,?)',
                [pname, status],
                function (err, results) {
                    //  响应数据
                    if (err) {
                        res.json({ code: 1, msg: "添加失败", data: { err } })
                    } else {
                        res.json({ code: 0, msg: "添加完成", data: { pname: pname, status: status } })
                    }
                    console.log(err + 'ok了!')
                });
        }
    })
})
// 用户类型删除
router.get('/delete/:id',(req,res) =>{
    console.log(req.params.id)
    db.query('DELETE FROM department WHERE id = ?',[parseInt(req.params.id)],
        function(error, result){
            if (error) {
                res.json({ code: 1, msg: "删除失败", data: { err } })
            } else {
                res.json({ code: 0, msg: "删除成功"})
            }
        }
    )
})
// 多个用户类型的删除、
router.get('/deletes/:id',(req,res) =>{
    console.log(req.params.id)
    let userids = req.params.id
    let useridps = JSON.parse(userids)
    // let tiaojian = `DELETE FROM users WHERE id in ${useridps}`
    // db.query(tiaojian,
    //     function(error, result){
    //         if (error) {
    //             res.json({ code: 1, msg: "删除失败", data: { err } })
    //         } else {
    //             res.json({ code: 0, msg: "删除成功"})
    //         }
    //     }
    // )
    let tiaojian = 'DELETE FROM department WHERE id IN (?)';
    db.query(tiaojian, [useridps], function (error, result) {
        if (error) {
            res.json({ code: 1, msg: "删除失败", data: { error: error } });
        } else {
            res.json({ code: 0, msg: "删除成功", data: { affectedRows: result.affectedRows } });
        }
    });
})
// 用户类型修改--获取信息
router.get('/edit/:id', (req, res) => {
    console.log(req.query,req.params)
    // 、！！！ get 取参数
    //  ?page=1&page_size=3,参数放在请求字符客户，问号开头的，req.query中 { page: '1', page_size: '3' }取
    //  /renyuan/edit/5 ,参数是动态路由 （/edit/:id），req.param中取参数 { id: '5' } 取
    if(!req.params.id){
        res.send({ code: 1, msg: '缺少参数' ,data: [] });
    }
    db.query(
        'SELECT * FROM department WHERE id = ?', [parseInt(req.params.id)], 
        function (error, result) {
            // 响应数据 ,扁平化数组 Array.flat(1)
            res.send({ code: 0, msg: '查询数据' ,data: result[0] });
        }
    );
})
// 用户类型修改 : 保存信息
router.post('/save_edit/:id', (req, res) => {
    // 声明body
    let id = req.params.id; //动态路由中的参数通过params取
    let { pname , status } = req.body; //普通提交的数据，在req.body中取到
    // 执行sql语句
    db.query('UPDATE department SET pname=?,status=? WHERE id=?',
        [pname, status,id], function () {
            // 响应信息
            res.json({ msg: "修改完毕", code: 0, data:{pname,status}})
        })
    // res.json({ msg: "人员修改", code: 1, data: [] })
})
module.exports = router;